package com.example.crm.controller.api;

import com.example.crm.entity.SalesTask;
import com.example.crm.vo.Result;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 销售任务API控制器
 */
@RestController
@RequestMapping("/api/sales/tasks")
public class SalesTaskAPIController {

    /**
     * 获取任务列表
     */
    @GetMapping("/list")
    public Result<List<Map<String, Object>>> list(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String priority,
            @RequestParam(required = false) Long assigneeId) {
        
        try {
            // 模拟任务数据
            List<Map<String, Object>> tasks = generateMockTasks();
            
            // 过滤任务
            if (status != null || priority != null || assigneeId != null) {
                tasks = tasks.stream()
                    .filter(task -> 
                        (status == null || status.isEmpty() || task.get("status").equals(status)) &&
                        (priority == null || priority.isEmpty() || 
                            ((String)task.get("priority")).toLowerCase().equals(priority.toLowerCase())) &&
                        (assigneeId == null || assigneeId.equals(task.get("assigneeId")))
                    )
                    .collect(Collectors.toList());
            }
            
            return Result.success(tasks);
        } catch (Exception e) {
            return Result.error("获取任务列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getById(@PathVariable Long id) {
        try {
            // 模拟任务数据
            List<Map<String, Object>> tasks = generateMockTasks();
            
            // 查找匹配ID的任务
            Optional<Map<String, Object>> task = tasks.stream()
                .filter(t -> t.get("id").equals(id))
                .findFirst();
                
            if (task.isPresent()) {
                return Result.success(task.get());
            } else {
                return Result.error("任务不存在");
            }
        } catch (Exception e) {
            return Result.error("获取任务详情失败: " + e.getMessage());
        }
    }

    /**
     * 添加任务
     */
    @PostMapping("/add")
    public Result<Boolean> save(@RequestBody Map<String, Object> params) {
        try {
            // 模拟保存任务
            // 在实际应用中，应该将任务保存到数据库
            
            return Result.success(true);
        } catch (Exception e) {
            return Result.error("添加任务失败: " + e.getMessage());
        }
    }

    /**
     * 更新任务
     */
    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody Map<String, Object> params) {
        try {
            // 模拟更新任务
            // 在实际应用中，应该更新数据库中的任务
            
            return Result.success(true);
        } catch (Exception e) {
            return Result.error("更新任务失败: " + e.getMessage());
        }
    }

    /**
     * 更新任务状态
     */
    @PutMapping("/status/{id}")
    public Result<Boolean> updateStatus(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        try {
            String status = (String)params.get("status");
            if (status == null || status.isEmpty()) {
                return Result.error("状态参数不能为空");
            }
            
            // 模拟更新任务状态
            // 在实际应用中，应该更新数据库中的任务状态
            
            return Result.success(true);
        } catch (Exception e) {
            return Result.error("更新任务状态失败: " + e.getMessage());
        }
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        try {
            // 模拟删除任务
            // 在实际应用中，应该删除数据库中的任务
            
            return Result.success(true);
        } catch (Exception e) {
            return Result.error("删除任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成模拟任务数据
     */
    private List<Map<String, Object>> generateMockTasks() {
        List<Map<String, Object>> tasks = new ArrayList<>();
        
        // 待办任务
        Map<String, Object> task1 = new HashMap<>();
        task1.put("id", 1L);
        task1.put("title", "跟进重点客户需求");
        task1.put("description", "与ABC公司跟进软件采购需求讨论");
        task1.put("status", "todo");
        task1.put("priority", "HIGH");
        task1.put("assigneeId", 101L);
        task1.put("assigneeName", "张三");
        task1.put("dueDate", LocalDate.now().plusDays(3).toString());
        tasks.add(task1);
        
        // 进行中任务
        Map<String, Object> task2 = new HashMap<>();
        task2.put("id", 2L);
        task2.put("title", "准备销售方案");
        task2.put("description", "为XYZ公司准备定制化销售方案");
        task2.put("status", "inprogress");
        task2.put("priority", "MEDIUM");
        task2.put("assigneeId", 102L);
        task2.put("assigneeName", "李四");
        task2.put("dueDate", LocalDate.now().plusDays(5).toString());
        tasks.add(task2);
        
        // 已完成任务
        Map<String, Object> task3 = new HashMap<>();
        task3.put("id", 3L);
        task3.put("title", "客户回访");
        task3.put("description", "对上月成交的客户进行回访");
        task3.put("status", "completed");
        task3.put("priority", "LOW");
        task3.put("assigneeId", 103L);
        task3.put("assigneeName", "王五");
        task3.put("dueDate", LocalDate.now().plusDays(7).toString());
        task3.put("completionDate", LocalDate.now().minusDays(1).toString());
        tasks.add(task3);
        
        // 添加更多任务
        Map<String, Object> task4 = new HashMap<>();
        task4.put("id", 4L);
        task4.put("title", "新市场调研");
        task4.put("description", "调研金融行业潜在客户需求");
        task4.put("status", "inprogress");
        task4.put("priority", "MEDIUM");
        task4.put("assigneeId", 104L);
        task4.put("assigneeName", "赵六");
        task4.put("dueDate", LocalDate.now().plusDays(10).toString());
        tasks.add(task4);
        
        return tasks;
    }
} 